import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;

class MyFile {
    Scanner sc;
    String path;
    boolean end = false;

    MyFile(String path) {
        try {
            this.path = path;
            sc = new Scanner(new FileReader(new File(path)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public ArrayList<Data> readBlock() {
        if (isEnd())
            return null;
        ArrayList<Data> result = new ArrayList<>();
        for (int i = 0; i < MergeSort.recordPerBlock; i++) {
            String line;
            if (!sc.hasNext()) {
                sc.close();
                if(!this.path.equals("data.txt"))
                    new File(this.path).delete();
                end = true;
                break;
            }
            line = this.sc.nextLine();
            String[] keyAndValue = line.split(" ");
            result.add(new Data(Integer.parseInt(keyAndValue[0]), keyAndValue[1]));
        }
        if (!end&&!sc.hasNext()) {//有可能正好读完文件最后一行,此时需要更新状态
            sc.close();
            if(!this.path.equals("data.txt"))
                new File(this.path).delete();
            end = true;
        }
        return result;
    }

    public boolean isEnd() {
        return end;
    }
}
